﻿@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>部门管理</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/layui/2.9.7/css/layui.css" />
    <style>
        .layui-table-cell {
            height: auto;
            line-height: 28px;
        }
    </style>
</head>
<body>
    <div class="layui-container" style="margin-top: 20px;">
        <!-- 搜索栏 -->
        <div class="layui-form">
            <div class="layui-form-item">
                <label class="layui-form-label">部门名称</label>
                <div class="layui-input-inline">
                    <input type="text" id="deptName" class="layui-input" placeholder="请输入部门名称" />
                </div>
                <label class="layui-form-label">校区</label>
                <div class="layui-input-inline">
                    <select id="campusSel" class="layui-select">
                        <!-- 动态加载校区选项 -->
                    </select>
                </div>
                <button class="layui-btn" id="searchBtn">查询</button>
                <button class="layui-btn layui-btn-normal" id="addBtn">添加</button>
            </div>
        </div>

        <!-- 部门列表 -->
        <table class="layui-table" id="deptTable" lay-size="sm" lay-filter="deptTable">
            <thead>
            </thead>
            <tbody></tbody>
        </table>
    </div>

    <!-- 新增/编辑模态框 -->
    <div id="deptModal" class="layui-form" style="display: none; padding: 20px;">
        <input type="hidden" id="deptId" />
        <div class="layui-form-item">
            <label class="layui-form-label">部门名称</label>
            <div class="layui-input-block">
                <input type="text" id="modalDeptName" class="layui-input" placeholder="请输入部门名称" lay-verify="required" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">校区</label>
            <div class="layui-input-block">
                <select id="modalCampusSel" class="layui-select" lay-verify="required">
                    <!-- 动态加载校区选项 -->
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">部门说明</label>
            <div class="layui-input-block">
                <textarea id="modalDeptDesc" class="layui-textarea" placeholder="请输入部门说明"></textarea>
            </div>
        </div>
    </div>

    <!-- 操作列模板 -->
    <script type="text/html" id="toolbarTpl">
        <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <script src="https://cdn.staticfile.org/layui/2.9.7/layui.js"></script>
    <script>
        layui.use(['table', 'form', 'jquery', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var $ = layui.$;
            var layer = layui.layer;

            // 初始化校区下拉框（搜索栏和模态框共用）
            loadCampusSelect("#campusSel");
            loadCampusSelect("#modalCampusSel");

            // 渲染部门表格
            renderDeptTable();

            // ---------- 方法定义 ----------

            // 加载校区下拉框（通用方法）
            function loadCampusSelect(selectId) {
                $.ajax({
                    url: "/Dept/GetCampusList", // 调用后端GetCampusList接口
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code !== 0) {
                            layer.msg(res.msg, { icon: 2 });
                            return;
                        }
                        $(selectId).empty();
                        var options = '<option value="0">全部</option>';
                        res.data.forEach(function (item) {
                            options += '<option value="' + item.CampusID + '">' + item.CampusName + '</option>';
                        });
                        $(selectId).html(options);
                        form.render('select');
                    },
                    error: function () {
                        layer.msg("加载校区失败", { icon: 2 });
                    }
                });
            }

            // 渲染部门表格（含搜索参数）
            function renderDeptTable() {
                table.render({
                    elem: "#deptTable",
                    url: "/Dept/GetDeptList", // 调用后端GetDeptList接口
                    method: "POST",
                    cols: [[
                        { field: 'DeptID', title: '编号', width: 80, sort: true },
                        { field: 'DeptName', title: '部门', width: 140 },
                        { field: 'CampusName', title: '校区名称', width: 150 },
                        { field: 'DeptReMark', title: '备注'}, // 匹配后端字段DeptReMark
                        { fixed: 'right', title: '操作', width: 200, templet: '#toolbarTpl' }
                    ]],
                    page: true,
                    limit: 10,
                    limits: [10, 20, 30],
                    where: {
                        DeptName: $("#deptName").val().trim(),
                        CampusID: $("#campusSel").val()
                    },
                    response: {
                        statusCode: 0, // 后端成功状态码
                        countName: 'count',
                        dataName: 'data'
                    },
                    done: function (res, curr, count) {
                        $(".layui-table-page .layui-laypage-info").text("显示第 " + curr + " 页，共 " + Math.ceil(count / 10) + " 页，总 " + count + " 条记录");
                    }
                });
            }

            // 搜索按钮点击事件
            $("#searchBtn").click(function () {
                renderDeptTable();
            });

            // 添加按钮点击事件
            $("#addBtn").click(function () {
                resetModal();
                loadCampusSelect("#modalCampusSel");

                layer.open({
                    type: 1,
                    title: "添加部门",
                    area: ["500px", "350px"],
                    content: $("#deptModal"),
                    btn: ["确认添加", "取消"],
                    btn1: function (index) {
                        var deptName = $("#modalDeptName").val().trim();
                        if (!deptName) {
                            $("#modalDeptName").addClass("layui-form-danger");
                            layer.tips('部门名称不能为空', '#modalDeptName', { tips: 1 });
                            return false;
                        }

                        var data = {
                            DeptName: deptName,
                            CampusID: $("#modalCampusSel").val(),
                            DeptReMark: $("#modalDeptDesc").val() // 匹配后端字段DeptReMark
                        };

                        $.ajax({
                            url: "/Dept/AddDept",
                            type: "POST",
                            data: data,
                            success: function (res) {
                                if (res.code === 0) {
                                    layer.msg(res.msg, { icon: 1 });
                                    layer.close(index);
                                    renderDeptTable();
                                } else {
                                    layer.msg(res.msg, { icon: 2 });
                                }
                            },
                            error: function () {
                                layer.msg("新增部门失败", { icon: 2 });
                            }
                        });
                    }
                });
            });

            // 表格工具事件（修改、删除）
            table.on('tool(deptTable)', function (obj) {
                var data = obj.data;
                var layEvent = obj.event;

                if (layEvent === 'edit') {
                    // 先获取部门详情
                    $.ajax({
                        url: "/Dept/GetDeptById",
                        type: "GET",
                        data: { id: data.DeptID },
                        dataType: "json",
                        success: function (res) {
                            if (res.code === 0) {
                                // 回显数据
                                $("#deptId").val(res.data.DeptID);
                                $("#modalDeptName").val(res.data.DeptName);
                                $("#modalCampusSel").val(res.data.CampusID || 0);
                                $("#modalDeptDesc").val(res.data.DeptRemark || "");
                                form.render('select');

                                layer.open({
                                    type: 1,
                                    title: "修改部门",
                                    area: ["500px", "350px"],
                                    content: $("#deptModal"),
                                    btn: ["确认修改", "取消"],
                                    btn1: function (index) {
                                        var deptName = $("#modalDeptName").val().trim();
                                        if (!deptName) {
                                            $("#modalDeptName").addClass("layui-form-danger");
                                            layer.tips('部门名称不能为空', '#modalDeptName', { tips: 1 });
                                            return false;
                                        }

                                        var data = {
                                            DeptID: $("#deptId").val(),
                                            DeptName: deptName,
                                            CampusID: $("#modalCampusSel").val(),
                                            DeptReMark: $("#modalDeptDesc").val()
                                        };

                                        $.ajax({
                                            url: "/Dept/UpdateDept",
                                            type: "POST",
                                            data: data,
                                            success: function (res) {
                                                if (res.code === 0) {
                                                    layer.msg(res.msg, { icon: 1 });
                                                    layer.close(index);
                                                    renderDeptTable();
                                                } else {
                                                    layer.msg(res.msg, { icon: 2 });
                                                }
                                            },
                                            error: function () {
                                                layer.msg("修改部门失败", { icon: 2 });
                                            }
                                        });
                                    }
                                });
                            } else {
                                layer.msg(res.msg, { icon: 2 });
                            }
                        },
                        error: function () {
                            layer.msg("获取部门详情失败", { icon: 2 });
                        }
                    });
                } else if (layEvent === 'del') {
                    layer.confirm('确定要删除部门【' + data.DeptName + '】吗？', {
                        icon: 3,
                        title: '删除确认'
                    }, function (confirmIndex) {
                        $.ajax({
                            url: "/Dept/DeleteDept",
                            type: "POST",
                            data: { id: data.DeptID }, // 匹配后端参数名id
                            success: function (res) {
                                if (res.code === 0) {
                                    layer.msg(res.msg, { icon: 1 });
                                    obj.del();
                                } else {
                                    layer.msg(res.msg, { icon: 2 });
                                }
                            },
                            error: function () {
                                layer.msg("删除部门失败", { icon: 2 });
                            }
                        });
                        layer.close(confirmIndex);
                    });
                }
            });

            // 重置模态框数据
            function resetModal() {
                $("#deptId").val("");
                $("#modalDeptName").val("").removeClass("layui-form-danger");
                $("#modalCampusSel").val("0");
                $("#modalDeptDesc").val("");
                form.render('select');
            }
        });
    </script>
</body>
</html>
